//
//  HuangwwAuthID.m
//  Huangww
//
//  Created by lee on 2019/4/15.
//  Copyright © 2019 Huangww. All rights reserved.
//

#import "HuangwwAuthID.h"
#import <UIKit/UIKit.h>
#import "HuangwwFaceAndGestureHeader.h"
#import <FuliBaseLibraryFramework/FuliBaseLibraryFramework.h>
#import "HuangwwPCCircleViewConst.h"
@implementation HuangwwAuthID

+ (instancetype)sharedInstance {
    static HuangwwAuthID *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HuangwwAuthID alloc] init];
    });
    return instance;
}

+ (void)showTouchIdWithTitle:(NSString *_Nullable)title falldBackTitle:(NSString *)falllBackTitle fallBackBlock:(TouchIdFallBackBlock)fallBackBlock resultBlock:(TouchIdResultBlock)resultBlock
{
    if(!title) {
        if(iPhoneX){
            title = @"验证已有面容";
        }else{
            title = @"通过Home键验证已有指纹";
        }
    }
    //初始化上下文对象
    LAContext *context = [[LAContext alloc] init];
    context.localizedFallbackTitle = falllBackTitle;
    //错误对象
    NSError* error = nil;
    NSString* result = title;
    //首先使用canEvaluatePolicy 判断设备支持状态
    if ([context canEvaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics
                             error:&error]) {
        [context evaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics
                localizedReason:result reply:^(BOOL success, NSError * _Nullable error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (success) {
                            !resultBlock ?: resultBlock(YES, YES,nil);
                        } else {
                            if (error.code == LAErrorUserFallback)
                            {
                                if (fallBackBlock) {
                                    fallBackBlock();
                                }
                            }
                            else
                            {
                                switch (error.code) {
                                    case LAErrorAuthenticationFailed:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"TouchID/FaceID 验证失败");
                                            //                                [MBProgressHUD showFailureProgress:[NSString stringWithFormat:@"您的手机还未设置%@,请去设置",iPhoneX ? @"FaceID" : @"指纹"]];
                                            
                                        });
                                        break;
                                    }
                                    case LAErrorUserCancel:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"TouchID/FaceID 被用户手动取消");
                                            
                                        });
                                    }
                                        break;
                                    case LAErrorUserFallback:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"用户不使用TouchID/FaceID,选择手动输入密码");
                                            
                                        });
                                    }
                                        break;
                                    case LAErrorSystemCancel:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"TouchID/FaceID 被系统取消 (如遇到来电,锁屏,按了Home键等)");
                                            
                                        });
                                    }
                                        break;
                                    case LAErrorPasscodeNotSet:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"TouchID/FaceID 无法启动,因为用户没有设置密码");
                                            [MBProgressHUD showFailureProgress:[NSString stringWithFormat:@"您的手机还未设置%@,请去设置",iPhoneX ? @"FaceID" : @"指纹"]];
                                            
                                        });
                                    }
                                        break;
                                        //case LAErrorTouchIDNotEnrolled:{
                                    case LAErrorBiometryNotEnrolled:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"TouchID/FaceID 无法启动,因为用户没有设置TouchID/FaceID");
                                            [MBProgressHUD showFailureProgress:[NSString stringWithFormat:@"您的手机还未设置%@,请去设置",iPhoneX ? @"FaceID" : @"指纹"]];
                                            
                                        });
                                    }
                                        break;
                                        //case LAErrorTouchIDNotAvailable:{
                                    case LAErrorBiometryNotAvailable:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"TouchID/FaceID 无效");
                                            
                                        });
                                    }
                                        break;
                                        //case LAErrorTouchIDLockout:{
                                    case LAErrorBiometryLockout:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"TouchID/FaceID 被锁定(连续多次验证TouchID/FaceID失败,系统需要用户手动输入密码)");
                                            //                                [MBProgressHUD showFailureProgress:[NSString stringWithFormat:@"%@被锁定,请到系统手动输入密码开启)",iPhoneX ? @"FaceID" : @"指纹"]];
                                            
                                        });
                                    }
                                        break;
                                    case LAErrorAppCancel:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"当前软件被挂起并取消了授权 (如App进入了后台等)");
                                            
                                        });
                                    }
                                        break;
                                    case LAErrorInvalidContext:{
                                        dispatch_async(dispatch_get_main_queue(), ^{
                                            NSLog(@"当前软件被挂起并取消了授权 (LAContext对象无效)");
                                            
                                        });
                                    }
                                        break;
                                    default:
                                        break;
                                }
                                !resultBlock ?: resultBlock(YES, NO, error);
                            }
                        }
                    });
                }];
    } else {
        if (error.code == LAErrorTouchIDLockout) {
//            [self tryShowTouchIdOrPwdInterface:title resultBlock:resultBlock];
            [MBProgressHUD showFailureProgress:[NSString stringWithFormat:@"多次错误，%@已被锁定，请到手机解锁界面输入密码",iPhoneX ? @"FaceID" : @"指纹"]];
        }
        error.code == LAErrorTouchIDNotEnrolled ? [MBProgressHUD showFailureProgress:[NSString stringWithFormat:@"%@没有设置，请到设置中设置",iPhoneX ? @"FaceID" : @"指纹"]] : @"";
        !resultBlock ?: resultBlock(NO, NO,error);
    }
}


+ (void)tryShowTouchIdOrPwdInterface:(NSString *)title resultBlock:(TouchIdResultBlock)resultBlock
{
    //初始化上下文对象
    LAContext *context = [[LAContext alloc] init];
    context.localizedFallbackTitle = @"";//不显示falldBack 按钮
    //错误对象
    NSError* error = nil;
    NSString* result = title;
    //使用kLAPolicyDeviceOwnerAuthentication才能弹出密码解锁界面
    if ([context canEvaluatePolicy:kLAPolicyDeviceOwnerAuthentication
                             error:&error]) {
        [context evaluatePolicy:kLAPolicyDeviceOwnerAuthentication
                localizedReason:result reply:^(BOOL success, NSError * _Nullable error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        !resultBlock ?: resultBlock(YES, success,error);
                    });
                }];
    } else {
        !resultBlock ?: resultBlock(NO, NO,error);
    }
}

/**
 返回当前指纹的的信息

 @return NSdata
 */
+ (NSData *)currentRAuthID{
    LAContext *context = [[LAContext alloc] init];
    NSError *error;
    if (![context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        NSLog(@"error:%@",error);
    }
    return context.evaluatedPolicyDomainState;
}


+ (void)RemoveAuthID {
    kRemoveUserDefaults(kAuthIDopen);
    kRemoveUserDefaults(kLockType);
}

+ (void)GestureOpen {
    kSetUserDefaults(@(1), kGestureOpen);
    kSetUserDefaults(@(1), kLockType);
}

+ (void)RemoveGesture {
    kRemoveUserDefaults(kGestureOpen);
    kRemoveUserDefaults(kLockType);
}

+ (void)SaveGesturePassword:(NSString *)gesture {
    kSetUserDefaults([self base64String:gesture], gestureFinalSaveKey);
}

+ (NSString *)GetGesturePassword {
    return [kGetUserDefaults(gestureFinalSaveKey) length] ? kGetUserDefaults(gestureFinalSaveKey) : @"";
}

+ (NSString *)base64String:(NSString *)str{
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64Encoded = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return base64Encoded;
}

@end
